package org.gaaidou.ptarmigan.springboot.core.async;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableConfigurationProperties(TaskProperties.class)
@EnableAsync
@ComponentScan("org.gaaidou.ptarmigan.springboot.core.async")
public class AsyncConfiguration {

    @Bean
    @Primary
    public ThreadPoolTaskExecutor asyncExecutor(@Autowired TaskProperties properties) {
        ThreadPoolTaskExecutor task = new ThreadPoolTaskExecutor();
        task.setThreadNamePrefix(properties.getPrefix());
        task.setCorePoolSize(calCorePoolSize(properties.getCorePoolSize()));
        task.setMaxPoolSize(task.getCorePoolSize() * 5);
        task.setKeepAliveSeconds(properties.getKeepAliveSeconds());
        task.setQueueCapacity(properties.getQueueCapacity());
        task.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        task.setTaskDecorator(new ThreadContextDecorator());
        return task;
    }


    private int calCorePoolSize(Integer corePooSize) {
        return Objects.requireNonNullElseGet(corePooSize, () -> Math.max(Runtime.getRuntime().availableProcessors() + 1, 2));
    }
}
